package com.jit.BluetoothKey.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.pm.PackageManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2018/1/29.
 *  蓝牙操作对象 单例模式 始终操作一个蓝牙对象
 */

public class  BluetoothHelper {
    private static BluetoothHelper instance ;
    public BluetoothAdapter bluetoothAdapter;  //本地蓝牙适配器
    private List<BluetoothDevice> devicesList = new ArrayList<>();

    private BluetoothHelper() {
    }
    public static BluetoothHelper getInstance(){
        if (instance==null){
            synchronized (BluetoothHelper.class){
                if (instance ==null){
                    instance = new BluetoothHelper();
                }
            }
        }
        return instance;
    }

    /**
     *  是否支持蓝牙设备
     */

    public boolean isSupportBluetooth(Context context){
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
    }

    /**
     *   获取设备（主要是手机）的蓝牙适配器
     */
    public void getBluetoothAdapt(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    /**
     *  开启蓝牙设备
     */
    public void openBluetooth(){
        if (!bluetoothAdapter.isEnabled()){
            bluetoothAdapter.enable();
        }
    }


    /**
     *  获取蓝牙上已经绑定的蓝牙设备
     */

    public List<BluetoothDevice> boundDevices(){
        if (bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices.size()>0){
            for (BluetoothDevice bluetoothDevice:bondedDevices){
                if (!devicesList.contains(bluetoothDevice)){
                    devicesList.add(bluetoothDevice);
                }
            }
        }
        return devicesList;
    }

    public void boundDevice(BluetoothDevice bluetoothDevice){
        bluetoothDevice.createBond();
    }

}
